package common

import "time"

const TimeStr = "2006-01-02 15:04:05.999"

/*
	### 判断两个时间戳是否同一天 ###
	28800: 当天东八区时间与格林尼治时间的时差(秒)
	86400: 一天的秒数
*/
func IsSameDay(t1 time.Time, t2 time.Time) bool {
	t1Unix := (t1.Unix() + 28800) / 86400
	t2Unix := (t2.Unix() + 28800) / 86400
	if t1Unix == t2Unix {
		return true
	}
	return false
}

/*
	### 获取某个月份有多少天 ###
*/
func GetMonthDay(year, month int) int {
	switch month {
	case 2:
		if year%4 == 0 && year%100 != 0 || year%400 == 0 {
			return 29
		} else {
			return 28
		}
	case 4, 6, 9, 11:
		return 30
	default:
		return 31
	}
}

/*
	### 定时任务
*/
func TimeCron(hour, min int) {
	now := time.Now()
	nowHour := now.Hour()
	nowMin := now.Minute()

	if nowHour < hour || (nowHour == hour && nowMin < min) {
		next := time.Date(now.Year(), now.Month(), now.Day(), hour, min, 0, 0, now.Location())
		t := time.NewTimer(next.Sub(now))
		<-t.C
		// TODO : Work
	}

	for {
		now = time.Now()
		next := now.Add(time.Hour * 24)
		next = time.Date(next.Year(), next.Month(), next.Day(), hour, min, 0, 0, next.Location())
		t := time.NewTimer(next.Sub(now))
		<-t.C
		// TODO : Work
	}
}

/*
	两个日期范围的所有字符串日期
*/
func GetDayRange(t1, t2 time.Time) []string {
	t := t2.Unix() - t1.Unix()
	gDay := t / 86400

	rangeList := make([]string, 0, gDay+1)
	for i := int64(0); i <= gDay; i++ {
		rangeList = append(rangeList, t1.Add(24*time.Hour*time.Duration(i)).Format("20060102"))
	}
	return rangeList
}

/*
	t, _ := time.Parse("20060102150405.999", "20150102122345.000")
	time.Time 转 20060102150405999
*/
func TimeToStr(t time.Time) string {
	t1 := t.Format("20060102150405")
	t2 := t.Format(".999")
	if len(t2) == 0 {
		t2 = "000"
	} else if len(t2) == 2 {
		t2 = t2[1:] + "00"
	} else if len(t2) == 3 {
		t2 = t2[1:] + "0"
	}
	return t1 + t2
}
